const OSS = require("ali-oss");
const uuid = require("uuid");
const Ret = require("./ret");
const Jimp = require("jimp");
const util = require("util");

module.exports = class Oss {
  static async upload(
    path,
    reqFileOrPath,
    prefix,
    accessKeyId,
    accessKeySecret,
    stsToken,
    region,
    bucket,
    toWidth
  ) {
    const client = new OSS({
      region: "oss-" + region,
      accessKeyId,
      accessKeySecret,
      stsToken,
      bucket,
      endpoint: "oss-" + region + ".aliyuncs.com",
    });
    let id = uuid.v4().replace(/-/g, "");
    let fileName, filePath, subfix;
    // 判断是否文本
    if (typeof reqFileOrPath == "string") {
      fileName = reqFileOrPath.split("/").pop();
      filePath = reqFileOrPath;
    } else {
      // 计算文件名
      fileName = reqFileOrPath.originalFilename;
      filePath = reqFileOrPath.path;
    }
    if (fileName.includes(".")) {
      subfix = fileName.split(".").pop();
    }

    if (toWidth) {
      let imageObject = await util.promisify(Jimp.read)(filePath);
      if (toWidth < imageObject.bitmap.width) {
        imageObject.resize(toWidth).write(filePath);
      }
    }
    let result = await client.put(
      path + "/" + prefix + "-" + id + "." + subfix,
      filePath
    );
    if (result.res.status == 200) {
      return new Ret(true).setData({ imgUrl: result.url });
    } else {
      return new Ret(false);
    }
  }
};
